<?php

namespace App\Http\Controllers\Innerend;


use App\Models\Fresh;
use App\Models\SiteSms;
use App\Models\User;
use App\Models\SiteType;
use App\Models\TopicSubscribe;
use App\Models\UserInvite;
use App\Models\UserVerify;
use App\Service\BaiduSMS;
use Illuminate\Support\Facades\Config;

class UserVerifyController extends BaseController
{
    // 成员管理
    public function initialize()
    {
        parent::initialize();
        $this->model = 'UserVerify';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作


    // 邀请记录
    public function _lists()
    {
        $where   = [];
        $uid     = $this->getData('uid', 0, 'intval');
        $verify  = $this->getData('verify', null, 'intval');
        $a_type  = $this->getData('apply_type', 0, 'intval');
        $keyword = $this->getData('keyword', null, 'trim');
        if($uid){
            $where[] = ['uid', '=', $uid];
        }
        if(!is_null($verify)){
            $where[] = ['verify', '=', $verify];
        }
        if($a_type){
            $where[] = ['apply_type', '=', $a_type];
        }
        if($keyword){
            $where[] = $this->orWhere('realname|position|areas|description', 'like', $keyword);
        }

        // 查询
        $verifyDb = new UserVerify();
        $result   = $verifyDb->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img'] = $this->getHeadImg($_info['head_img'] ?? '');
                }

                // 整理
                $result['list'][$key]['user']       = $_info;
                $result['list'][$key]['apply_type'] = $types[$item['apply_type']]['name'] ?? '';
                $result['list'][$key]['areas']      = json_decode($item['areas'], 1);
                $result['list'][$key]['files']      = json_decode($item['files'], 1);
                $result['list'][$key]['links']      = json_decode($item['links'], 1);
            }
        }

        return $this->success($result);
    }


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        // 用户
        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 身份认证类型
        $typeDb   = new SiteType();
        $typeList = $typeDb->isCache(true)->getAll(['channel' => 'user_type']);
        $types    = array_column($typeList, 'name', 'id');
        $verifys  = [0 => '待审核', 1 => '审核通过', 2 => '审核不通过'];

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid       = $item['uid'];
            $_user      = $users[$_uid] ?? [];
            $_id        = $item['id'];
            $verify     = $verifys[$item['verify']];
            $apply_type = $types[$item['apply_type']] ?? '-';

            // 操作
            $operate = $listHtml->operate_edit(['id' => $_id], '审核');
            //$operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该申请吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($_user['username']);
            $tr .= $listHtml->list_td($item['realname']);
            $tr .= $listHtml->list_td($apply_type);
            $tr .= $listHtml->list_td($item['position']);
            $tr .= $listHtml->list_td($verify);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        return ['uid' => ['用户', 80], 'apply_type' => ['申请类型', 120], 'realname' => '真实姓名', 'position' => '职位头衔', 'verify' => ['审核状态', 80], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $addUrl     = url('/innerend/'.$this->controller.'/add');
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加</a> ';
        $this->assign('top_button', '');
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();
        $uid  = $info['uid'] ?? 0;

        // 用户名
        $userDb = new User();
        $user   = $userDb->isCache(true)->getOneById($uid);

        // 身份认证类型
        $typeDb   = new SiteType();
        $typeList = $typeDb->isCache(true)->getAll(['channel' => 'user_type']);
        $types    = array_column($typeList, 'name', 'id');
        $verifys  = [0 => '待审核', 1 => '审核通过', 2 => '审核不通过'];


        // 三个json
        $areas = json_decode($info['areas'] ?? "[]", true);
        $files = json_decode($info['files'] ?? "[]", true);
        $links = json_decode($info['links'] ?? "[]", true);
        $areas = $form->formShow(implode(',', $areas));  //?
        $files = $form->formShow(implode(',', $files));  //?
        $links = $form->formShow(implode(',', $links));  //?

        $uidHtml     = $form->formHidden('uid', $uid);
        $username    = $form->formShow($user['username'] ?? '');
        $apply_type  = $form->formShow($types[$info['apply_type'] ?? ''] ?? '-');
        $position    = $form->formShow($info['position'] ?? '');
        $description = $form->formShow($info['description'] ?? '');
        $verify      = $form->formRadio('verify', $info['verify'] ?? 1, [1 => '审核通过', 2 => '审核不通过']);
        $content     = $form->formTextarea('audit_content', $info['audit_content'] ?? '');
        $_id         = $form->formHidden('id', $info['id'] ?? '');

        $html .= $uidHtml;
        $html .= $form->makeItem('用户名', $username);
        $html .= $form->makeItem('申请类型', $apply_type);
        $html .= $form->makeItem('职位头衔', $position);
        $html .= $form->makeItem('描述', $description);
        $html .= $form->makeItem('关注领域', $areas);
        $html .= $form->makeItem('证明文件', $files);
        $html .= $form->makeItem('网络连接（其他证明）', $links);
        $html .= $form->makeItem('审核状态', $verify);
        $html .= $form->makeItem('审核内容', $content);
        $html .= $_id;

        return $html;
    }


    // 审核操作
    public function toVerify()
    {
        $_id     = $this->id;
        $verify  = $this->getData('verify', null, 'intval');
        $content = $this->getData('content', null, 'trim');

        $verifyDb = new UserVerify();
        $userInfo = $verifyDb->onVerify($_id, $verify, $content);
        $this->throwReturn($userInfo === false, $verifyDb->getError());

        // 发送通知短信
        // sms-tmpl-asrGtf70927 验证码  code
        // sms-tmpl-UXmJiz55799 身份认证 name  content
        // sms-tmpl-jRdZOE16549 访谈预约 name
        //$mobile = 18086843363;
        //$mobile = 13981983854;
        $mobile  = $userInfo['mobile'];
        $name    = $userInfo['realname'] ?: $userInfo['username'];
        $temp    = 'sms-tmpl-UXmJiz55799';
        $content = $verify == 1 ? '审核通过，欢迎您继续参与财经记者社区交流' : '审核未通过，请重新认证';
        $send    = ['name' => $name, 'content' => $content,];

        // 发送短信操作
        $res = $this->baiduSms($mobile, $temp, $send);

        return $this->success($res, '审核操作成功！！');
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            'uid'           => $this->getData('uid', 0, 'intval'),
            'verify'        => $this->getData('verify', 1, 'intval'),
            'audit_content' => $this->getData('verify', '', 'trim'),
        ];

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'id'            => $this->getData('id', 0, 'intval'),
            'uid'           => $this->getData('uid', 0, 'intval'),
            'verify'        => $this->getData('verify', 1, 'intval'),
            'audit_content' => $this->getData('verify', '', 'trim'),
        ];

        // 检查唯一性

        return $data;
    }

}


